package com.itheima.service.impl;

import com.itheima.annotation.Log;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class DeptServiceImpl implements DeptService {

    private final DeptMapper deptMapper;
    private final EmpMapper empMapper;
    private final DeptLogService deptLogService;

    @Log
    @Override
    public List<Dept> list() {
        log.info("查询部门列表");
        return deptMapper.list();
    }

    /**
     * 删除部门
     *
     * @param id
     */
    @Override
    @Transactional
    public void delectDeptById(Integer id) {
        try {
            //根据部门id删除部门信息
            deptMapper.deleteById(id);
            //模拟：异常
//            if (true) {
//                int i = 1 / 0;
//            }
            //删除部门下的所有员工信息
            empMapper.deleteById(id);
        } finally {
            //不论是否有异常，最终都要执行的代码：记录日志
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作，此时解散的是" + id + "号部门");
            //调用其他业务类中的方法
            deptLogService.insert(deptLog);
        }
    }

    /**
     * 添加部门
     *
     * @param dept
     */
    @Log
    @Override
    public void addDept(Dept dept) {
        log.info("添加部门,{}", dept);
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insertDept(dept);
    }

    /**
     * 查询部门信息
     *
     * @param id
     * @return
     */
    @Log
    @Override
    public Dept getDeptById(Integer id) {
        return deptMapper.getDeptById(id);
    }
}
